import axios from 'axios'

const service = axios.create({
    baseURL: "http://localhost:8090",
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        config.url = config.url.includes('?') ? config.url + '&Token=' + localStorage.getItem('token') : config.url + '?Token=' + localStorage.getItem('token')
        config.headers['Token'] = localStorage.getItem('token')
        return config
    },
    error => {
        // 请求错误处理
        console.log('Request Error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        if (response.data.code == 401) {
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            window.location.href = '/login'
        } else {
            return response.data
        }
    },
    error => {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        window.location.href = '/login'
        return Promise.reject(error)
    }
)

export default service
